<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="searchData" layout="inline">
            <a-form-item label="发货单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="searchData.stockOutCode"/>
            </a-form-item>
            <a-form-item label="发货类型">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="searchData.stockOutTypeName"/>
            </a-form-item>
            <a-form-item label="流转卡号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="searchData.circulatCard"/>
            </a-form-item>
            <a-form-item label="发货流转卡">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="searchData.deliverCirculatCard"/>
            </a-form-item>
            <!-- <a-form-item label="订单号">
                <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="searchData.stockInCod" />
            </a-form-item> -->
            <a-form-item label="计划单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="searchData.planOrderCode"/>
            </a-form-item>
            <a-form-item label="客户名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="searchData.customName"/>
            </a-form-item>
            <a-form-item label="布号">
              <a-input allow-clear :style="{ width: '228px' }" class="bacClass" v-model="searchData.clothCode"/>
            </a-form-item>
            <a-form-item label="发货日期">
              <a-date-picker popup-container="html" :style="{ width: '200px' }" class="bacClass"
                             v-model="searchData.beginDate"/>
            </a-form-item>
            <a-form-item label="至">
              <a-date-picker popup-container="html" :style="{ width: '256px' }" class="bacClass"
                             v-model="searchData.endDat"/>
            </a-form-item>
          </a-form>
        </div>

      </div>
      <div style="text-align: end;">
        <Toolbar :items="toolbarList" @select="selectHandler" @audit="auditProductInStock" @del="delProductInStocks"
                 @add="addHandler"></Toolbar>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" type="card" :justify="true" :default-active-key="tabsKeys" @change="tabsChanges">
        <a-tab-pane title="未处理" :key="1">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           @grid-ready="gridReady" style="height: calc(100% - 45px)"
                           :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="tableDataList"
                           :columnDefs="inStockColDefs" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="searchData.total" show-total show-jumper
                           show-page-size @change="pageChange" style="justify-content: center"
                           :page-size="searchData.size"
                           :current="searchData.current" @page-size-change="change"/>
        </a-tab-pane>
        <a-tab-pane title="已处理" :key="2">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           @grid-ready="gridReady1" style="height: calc(100% - 45px)"
                           :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="tableDataList1"
                           :columnDefs="inStockColDefs1" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="detailData.total" show-total show-jumper
                           show-page-size @change="pageChange1" style="justify-content: center"
                           :page-size="detailData.size"
                           :current="detailData.current" @page-size-change="change1"/>
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" height="90%" :visible="pageData.showAdd"
              unmountOnClose @ok="handleOk" @cancel="pageData.showAdd = false" cancel-text='关闭' ok-text='保存'
              placement="bottom">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="width:100%;height:10%;float: right">
        <a-space>
          <a-form size="small" ref="formRef" :model="inStockData" layout="inline">

            <a-form-item label="发货日期">
              <a-date-picker popup-container="html" class="bacClass" :style="{ width: '200px' }"
                             v-model="inStockData.stockOutDate"/>
            </a-form-item>
            <a-form-item label="仓库名称" field="warehouseName" :rules="[{ required: true, message: '仓库名称必填' }]">
              <a-select popup-container="html" :style="{ width: '188px' }" class="bacClass" :allowClear="true"
                        @search="handleSearch"
                        v-model="inStockData.warehouseName" :filter-option="false" allow-search @focus="focusSel"
                        @change="chanON">
                <a-option v-for="item in pageData.nameList" :value="item['warehouseName']">{{
                    item['warehouseName']
                  }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="发货单号">
              <a-input allow-clear disabled :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="inStockData.stockOutCode"/>
            </a-form-item>
            <a-form-item label="流转卡号" field="circulatCard" :rules="[{ required: true, message: '流转卡号必填' }]">
              <a-input allow-clear :style="{ width: '188px' }" class="bacClass"
                       v-model.trim="inStockData.circulatCard" @press-enter="huiche" @change="changeLZ"/>
            </a-form-item>
            <a-form-item label="客户名称">
              <a-input allow-clear disabled :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="inStockData.customName"/>
            </a-form-item>
            <a-form-item label="计划单号">
              <a-input allow-clear disabled :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="inStockData.planOrderCode"/>
            </a-form-item>
            <a-form-item label="发货类型" field="stockOutTypeId" :rules="[{ required: true, message: '发货类型必填' }]">
              <a-select popup-container="html" :style="{ width: '188px' }" class="bacClass" allow-search
                        :filter-option="false"
                        v-model="inStockData.stockOutTypeId" :allowClear="true" @change="changeLX">
                <a-option :value="101">成品入库</a-option>
                <a-option :value="102">生产退库</a-option>
                <a-option :value="103">客户退库</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="发货流转卡号">
              <a-input allow-clear disabled :style="{ width: '172px' }" class="bacClass"
                       v-model.trim="inStockData.rawCirculatCard"/>
            </a-form-item>
            <a-form-item label="送货车号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="inStockData.deliverCarNo"/>
            </a-form-item>
            <a-form-item label="送货地址">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                       v-model.trim="inStockData.deliverAddress"/>
            </a-form-item>
            <a-form-item label="送货人">
              <a-input allow-clear :style="{ width: '214px' }" class="bacClass"
                       v-model.trim="inStockData.deliverPerson"/>
            </a-form-item>
            <a-form-item label="备注">
              <a-input allow-clear :style="{ width: '228px' }" class="bacClass" v-model="inStockData.remark"/>
            </a-form-item>
          </a-form>
        </a-space>
      </div>
      <!-- <div style="width:98%;height:26%;float: right"> -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                       @grid-ready="summaryGridReady" style="height:45%"
                       class='ag-theme-alpine' :defaultColDef="detailDefaultColDef" :rowData="summaryList"
                       :columnDefs="summaryColDefs"
                       :localeText="localeText1">
      </AgGridVuesCopys>
      <!-- </div> -->
      <!-- <div style="width:98%;height:62%;float: right"> -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                       @grid-ready="detailGridReady" style="height:45%;margin-top: 5%;"
                       class='ag-theme-alpine' :defaultColDef="detailDefaultColDef" :rowData="detailList"
                       :columnDefs="detailColDef"
                       :localeText="localeText1">
      </AgGridVuesCopys>
      <!-- </div> -->
    </a-drawer>
    <a-modal v-model:visible="pageData.showDetails" :width="800">
      <template #title> 入库详细</template>
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" @grid-ready="dtGridReady"
                       style="height:400px"
                       class='ag-theme-alpine' :defaultColDef="detailDefaultColDef" :rowData="tableDetailList"
                       :columnDefs="detailColDef" :localeText="localeText1">
      </AgGridVuesCopys>
    </a-modal>
  </pageTabelLayout>
</template>
<script setup lang="ts">
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from "@/hooks/table";
import {ref, reactive} from "vue"
import {post, get} from "@/api/http"
import {localeText} from '@/api/aggridZw'

import Toolbar from "@/components/Toolbar.vue"
import {Message, Modal} from "@arco-design/web-vue"
import {FormInstance} from "@arco-design/web-vue/es/form";
import dayjs from 'dayjs'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import {pagingList} from "@/api/paging";

const pagingList1: any = ref(pagingList)
const headerShow = ref(true)
const localeText1: any = ref(localeText)
const tableDataList = ref([])
const summaryList = ref([])
const detailList = ref([])
const tableDetailList = ref([])
const tableDataList1 = ref([])
const toolbarList: any = ref(['查询', '新增', '删除', '审核', '打印'])

const pager = reactive({
  total: 10,
  size: 10,
  page: 1
})

const pager1 = reactive({
  total: 10,
  size: 10,
  page: 1
})

const pageData = reactive({
  showAdd: false,
  showDetails: false,
  isShow: false,
  rHeight: 0,
  sideTitle: '新增成品出库',
  nameList: []
})


const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const detailDefaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}


const inStockColDefs = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '仓库名称',
    field: 'warehouseName',
    width: 120
  },
  {
    headerName: '发货单号',
    field: 'stockOutCode',
    width: 120
  },
  {
    headerName: '客户名称',
    field: 'customName',
    width: 120
  },
  {
    headerName: '发货日期',
    field: 'stockOutDate',
    width: 120
  },
  {
    headerName: '客户订单号',
    field: 'customOrderCode',
    width: 120
  },
  {
    headerName: '发货类型',
    field: 'stockOutTypeName',
    width: 150
  },
  {
    headerName: '客订名称',
    field: 'customOrderName',
    width: 120
  },
  {
    headerName: '流转卡号',
    field: 'circulatCard',
    width: 120
  },
  {
    headerName: '发货流转卡号',
    field: 'deliverCirculatCard',
    width: 120
  },
  {
    headerName: '送货车号',
    field: 'deliverCarNo',
    width: 120
  },
  {
    headerName: '送货人',
    field: 'deliverPerson',
    width: 120
  },
  {
    headerName: '布号',
    field: 'clothCode',
    width: 120
  },
  {
    headerName: '品名',
    field: 'brandName',
    width: 120
  },
  {
    headerName: '色号',
    field: 'colorCode',
    width: 120
  },
  {
    headerName: '色称',
    field: 'colorName',
    width: 120
  },
  {
    headerName: '投染重量',
    field: 'castDeyWeight',
    width: 150
  },
  {
    headerName: '投染匹数',
    field: 'castDeyHorseNum',
    width: 150
  },
  {
    headerName: '成品毛重',
    field: 'productGrossWeight',
    width: 150
  },
  {
    headerName: '审核状态',
    field: 'auditState',
    pinned: 'right',
    width: 120,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag type="success" class="gesture">未审核</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          auditState: props.params.data.auditState
        }
      }
    }
  },
]
const inStockColDefs1 = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '仓库名称',
    field: 'warehouseName',
    width: 120
  },
  {
    headerName: '发货单号',
    field: 'stockOutCode',
    width: 120
  },
  {
    headerName: '客户名称',
    field: 'customName',
    width: 120
  },
  {
    headerName: '发货日期',
    field: 'stockOutDate',
    width: 120
  },
  {
    headerName: '客户订单号',
    field: 'customOrderCode',
    width: 120
  },
  {
    headerName: '发货类型',
    field: 'stockOutTypeName',
    width: 150
  },
  {
    headerName: '客订名称',
    field: 'customOrderName',
    width: 120
  },
  {
    headerName: '流转卡号',
    field: 'circulatCard',
    width: 120
  },
  {
    headerName: '发货流转卡号',
    field: 'deliverCirculatCard',
    width: 120
  },
  {
    headerName: '送货车号',
    field: 'deliverCarNo',
    width: 120
  },
  {
    headerName: '送货人',
    field: 'deliverPerson',
    width: 120
  },
  {
    headerName: '布号',
    field: 'clothCode',
    width: 120
  },
  {
    headerName: '品名',
    field: 'brandName',
    width: 120
  },
  {
    headerName: '色号',
    field: 'colorCode',
    width: 120
  },
  {
    headerName: '色称',
    field: 'colorName',
    width: 120
  },
  {
    headerName: '投染重量',
    field: 'castDeyWeight',
    width: 150
  },
  {
    headerName: '投染匹数',
    field: 'castDeyHorseNum',
    width: 150
  },
  {
    headerName: '成品毛重',
    field: 'productGrossWeight',
    width: 150
  },
  {
    headerName: '审核状态',
    field: 'auditState',
    pinned: 'right',
    width: 120,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag type="success" class="gesture">已审核</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          auditState: props.params.data.auditState
        }
      }
    }
  },
]


const summaryColDefs = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '客户名称',
    field: 'customName',
    width: 150
  },
  {
    headerName: '流转卡号',
    field: 'circulatCard',
    width: 150
  },
  {
    headerName: '原流转卡号',
    field: 'rawCirculatCard',
    width: 150
  },
  {
    headerName: '发货流转卡号',
    field: 'deliverCirculatCard',
    width: 150
  },
  {
    headerName: '库位',
    field: 'storageName',
    width: 150
  },
  {
    headerName: '布号',
    field: 'clothCode',
    width: 150
  },
  {
    headerName: '品名',
    field: 'brandName',
    width: 150
  },
  {
    headerName: '色号',
    field: 'colorCode',
    width: 150
  },
  {
    headerName: '色称',
    field: 'colorName',
    width: 150
  },
  {
    headerName: '确认色',
    field: 'affirmColor',
    width: 150
  },
  {
    headerName: '投染重量',
    field: 'castDyeWeight',
    width: 150
  },
  {
    headerName: '投染匹数',
    field: 'castDyeHorseNum',
    width: 150
  },
  {
    headerName: '成品毛重',
    field: 'productGrossWeight',
    width: 150
  },
  {
    headerName: '成品匹数',
    field: 'castDyeHorseNum',
    width: 150
  },
  {
    headerName: '门幅',
    field: 'wdith',
    width: 150
  },
  {
    headerName: '克重',
    field: 'gramWeight',
    width: 150
  },
  {
    headerName: '计划单号',
    field: 'planOrderCode',
    width: 150
  },
  {
    headerName: '结算方式',
    field: 'settleWay',
    width: 150
  },
  {
    headerName: '结算数量',
    field: 'castDyeWeight',
    width: 150
  },
  {
    headerName: '结算单位',
    field: 'settleUnit',
    width: 150
  },
  {
    headerName: '单价',
    field: 'price',
    width: 150
  },
  {
    headerName: '金额',
    field: 'amount',
    width: 150
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 150
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 150
  },
  {
    headerName: '备注',
    field: 'remark',
    width: 150
  },
]


const detailColDef = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '条形码',
    field: 'barcode',
    width: 150
  },
  {
    headerName: '流转卡号',
    field: 'circulatCard',
    width: 150
  },
  {
    headerName: '匹号',
    field: 'horseNo',
    width: 150
  },
  {
    headerName: '毛重',
    field: 'grossWeight',
    width: 150
  },
  {
    headerName: '毛米数',
    field: 'grossMetreNum',
    width: 150
  },
  {
    headerName: '净重',
    field: 'netWeight',
    width: 150
  },
  {
    headerName: '净米数',
    field: 'netMetreNum',
    width: 150
  },
  {
    headerName: '检验等级',
    field: 'grade',
    width: 150
  },
  {
    headerName: '坯布匹数',
    field: 'horseNum',
    width: 150
  },
  {
    headerName: '坯布重量',
    field: 'netWeight',
    width: 150
  },
  {
    headerName: '坯布条形码',
    field: 'clothfiyCode',
    width: 150
  },
  {
    headerName: '布票号',
    field: 'clothVoteCode',
    width: 150
  },
  {
    headerName: '门幅',
    field: 'width',
    width: 150
  },
  {
    headerName: '克重',
    field: 'gramWeight',
    width: 150
  },
  {
    headerName: '结算重量',
    field: 'settleWeight',
    width: 150
  },
  {
    headerName: '结算单位',
    field: 'settleUnit',
    width: 150
  },
  {
    headerName: '出货长度',
    field: 'shipLength',
    width: 150
  },
  {
    headerName: '出货长度单位',
    field: 'shipLengthUnit',
    width: 150
  },
  {
    headerName: '出货重度',
    field: 'shipWeight',
    width: 150
  },
  {
    headerName: '出货重度单位',
    field: 'shipWeightUnit',
    width: 150
  },
  {
    headerName: '库位',
    field: 'storageName',
    width: 150
  },
  {
    headerName: '托盘编号',
    field: 'shelveCode',
    width: 150
  }
]


const searchData = reactive({
  circulatCard: '',
  customName: '',
  stockInCod: '',
  planOrderCode: '',
  clothCode: '',
  deliverCirculatCard: '',
  stockOutTypeName: '',
  stockOutCode: '',
  total: 10,
  current: 1,
  size: 10,
  deleteState: 0,
  beginDate: '',
  endDat: '',
  auditState: 0
})

const detailData = reactive({
  companyId: null,
  planOrderCode: null,
  customName: null,
  flowCardCode: null,
  stockInNo: null,
  warehouseId: '',
  total: 10,
  current: 1,
  size: 10
})


const inStockData = reactive({
  companyId: '',
  stockOutCode: '',
  customName: '',
  stockOutDate: '',
  stockOutTypeName: '',
  stockOutTypeId: null,
  planOrderCode: '',
  circulatCard: '',
  remark: '',
  warehouseName: '',
  warehouseId: '',
  rawCirculatCard: '',
  deliverCarNo: '',
  deliverAddress: '',
  deliverPerson: '',
  ProductStockOutDetail: []
})


const warehouseList = ref([{
  warehouseName: '',
  warehouseTypeId: '',
  id: '',
}])


const loadWarehouses = () => {
  post({
    url: 'dwWms/warehouse/getWarehouseByPara',
    data: {firmId: searchData['companyId'], warehouseTypeId: 13}
  }).then(({code, data}) => {
    if (code === 200) {
      warehouseList.value = data
      console.log(warehouseList.value)
    }
  })
}

onMounted(() => {
  post({
    url: 'dwWms/dwDyeProductInstock/fetchUserInfoByToken',
    data: {}
  }).then(({code, message, data}) => {
    if (code === 200) {
      //formData.companyId = data.firmId;
      searchData['companyId'] = data.firmId;
      loadWarehouses();
      loadInStocks();
      loadPagedStockDetails();
    } else {
      Message.error({
        content: message,
        duration: 5000,
      });
    }
  })
});


const tabsKeys = ref(1);
const tabsChanges = (e: any) => {
  tabsKeys.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '新增', '审核', '删除']
    loadInStocks();
  } else if (e == 2) {
    toolbarList.value = ['查询']
    loadPagedStockDetails();
  }
}

//切换TAB，执行不同查询
const selectHandler = () => {
  console.log(tabsKeys.value);
  if (tabsKeys.value == 1) {
    loadInStocks();
  } else if (tabsKeys.value == 2) {
    loadPagedStockDetails();
  }
  // loadInStocks()
}


const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api;
}


const loadInStocks = () => {
  post({
    url: '/dwWms/ProductStockOut/getPage',
    data: {
      circulatCard: searchData.circulatCard,
      customName: searchData.customName,
      stockOutCode: searchData.stockOutCode,
      planOrderCode: searchData.planOrderCode,
      clothCode: searchData.clothCode,
      stockOutTypeName: searchData.stockOutTypeName,
      deliverCirculatCard: searchData.deliverCirculatCard,
      page: pagination.page,
      size: pagination.pageSize,
      deleteState: 0,
      beginDate: searchData.beginDate,
      endDat: searchData.endDat,
      auditState: 0
    }
  }).then(({code, data}) => {
    if (code === 200) {
      gridOption.value.setRowData(data.list);
      searchData.total = data.total;
    }
  })
}


//入库明细
const gridOption1 = ref()
const gridReady1 = (params: any) => {
  gridOption1.value = params.api;
}

//入库明细
const loadPagedStockDetails = () => {
  post({
    url: '/dwWms/ProductStockOut/getPage',
    data: {
      circulatCard: searchData.circulatCard,
      customName: searchData.customName,
      stockOutCode: searchData.stockOutCode,
      planOrderCode: searchData.planOrderCode,
      clothCode: searchData.clothCode,
      stockOutTypeName: searchData.stockOutTypeName,
      deliverCirculatCard: searchData.deliverCirculatCard,
      page: pagination.page,
      size: pagination.pageSize,
      deleteState: 0,
      beginDate: searchData.beginDate,
      endDat: searchData.endDat,
      auditState: 1
    }
  }).then(({code, data}) => {
    if (code === 200) {
      gridOption1.value.setRowData(data.list);
      detailData.total = data.total;
    }
  })
}


//入库列表，操作-详细
const dtGridOptions = ref()
const dtGridReady = (params: any) => {
  dtGridOptions.value = params.api;
  params.columnApi.setColumnVisible('flowCardCode_1', false);
}


//新增界面，查询坯布出库记录及汇总
const summaryGridOptions = ref()
const summaryGridReady = (params: any) => {
  summaryGridOptions.value = params.api;
}


const detailGridOptions = ref();
const detailGridReady = (params: any) => {
  detailGridOptions.value = params.api;

}


// const handleOk = () => {
//     pageData.showAdd = false;
// };
const handleCancel = () => {
  pageData.showAdd = false;
}


const pageChange = (val: any) => {
  searchData.current = val;
  loadInStocks();
}

const pageChange1 = (val: any) => {
  detailData.current = val;
  loadPagedStockDetails();
}

function change(val: any) {
  searchData.size = val;
  loadInStocks();
}

function change1(val: any) {
  detailData.size = val;
  loadPagedStockDetails();
}

const totalRow = reactive([{
  barCode: '合计',
  grossWeight: 0,
  netWeight: 0,
  grossLength: 0,
  netLength: 0,
  outputWeight: 0,
  outputLength: 0
}])

//新增明细列表底部合计行
const createTotalRow = (data: any) => {
  totalRow[0].grossWeight = 0;
  totalRow[0].netWeight = 0;
  totalRow[0].grossLength = 0;
  totalRow[0].netLength = 0;
  totalRow[0].outputWeight = 0;
  totalRow[0].outputLength = 0;
  data.forEach((c: any) => {
    totalRow[0].grossWeight = totalRow[0].grossWeight + c.grossWeight;
    totalRow[0].netWeight = totalRow[0].netWeight + c.netWeight;
    totalRow[0].grossLength = totalRow[0].grossLength + c.grossLength;
    totalRow[0].netLength = totalRow[0].netLength + c.netLength;
    totalRow[0].outputWeight = totalRow[0].outputWeight + c.outputWeight;
    totalRow[0].outputLength = totalRow[0].outputLength + c.outputLength;
  });
  totalRow[0].grossWeight = Math.round(totalRow[0].grossWeight * 100) * 0.01;
  totalRow[0].netWeight = Math.round(totalRow[0].netWeight * 100) * 0.01;
  detailGridOptions.value.setPinnedBottomRowData(totalRow);
}


//新增入库记录，入库按钮执行
const formRef = ref<FormInstance>();
const handleOk = () => {
  // if (summaryList.value.length == 0) {
  //     Message.warning('请先录入流转卡号查询入库明细，无明细汇总无法入库！')
  //     return;
  // }
  // let inStock = Object.assign(summaryList.value[0], {
  //     warehouseId: inStockData.warehouseId,
  //     location: inStockData.location, stockInType: inStockData.stockInType, companyId: searchData.companyId
  // })
  formRef.value?.validate().then((err) => {
    if (!err) {
      // let stadey: boolean = true
      // stadey = summaryList.value.every((item: any) => {
      //     return item.storageId && item.shelveId
      // })
      // if (stadey) {
      summaryList.value.map((item: any) => {
        delete item.id;
      })
      inStockData.ProductStockOutDetail = summaryList.value
      if (pageData.sideTitle == "新增成品出库") {
        post({
          url: '/dwWms/ProductStockOut/insertList',
          data: inStockData
        }).then(({code, data, message}) => {
          if (code === 200) {
            formRef.value?.resetFields();
            loadInStocks();
            pageData.showAdd = false;
            Message.success({
              content: "新增成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: message,
              duration: 5000,
            });
          }
        })
      } else {
        post({
          url: '/dwWms/ProductStockIn/insertList',
          data: inStockData
        }).then(({code, data, message}) => {
          if (code === 200) {
            formRef.value?.resetFields();
            loadInStocks();
            pageData.showAdd = false;
            Message.success({
              content: "修改成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: message,
              duration: 5000,
            });
          }
        })
      }
      // } else {
      //     Message.error({
      //         content: '请完整填写库位(不可遗漏)！',
      //         duration: 5000,
      //     });
      //     return
      // }

    }
  });

}

//审核入库记录并增加库存记录
const auditProductInStock = () => {
  let rowsData = gridOption.value.getSelectedRows();
  if (rowsData.length === 0) {
    Message.warning("请选择要审核出库的记录！");
    return;
  }
  // else if (rowsData[0].status == 1) {
  //     Message.warning("数据已审核入库，不能再次审核！");
  //     return;
  // }
  post({
    url: '/dwWms/ProductStockOut/setAudit',
    data: rowsData.map((item: any) => {
      return {id: item.id, auditState: 1}
    })
  }).then(({code, message, data}) => {
    if (code === 200) {
      Message.success({
        content: "审核入库成功",
        duration: 5000,
      });
      loadInStocks();
    } else {
      Message.error({
        content: message,
        duration: 5000,
      });
    }
  })
}


//删除入库记录，逻辑删除
const delProductInStocks = () => {
  let rowDatas = gridOption.value.getSelectedRows();
  let rowIds = rowDatas.map((item: any) => item.id)
  if (rowIds.length === 0) {
    Message.warning("请选择要删除的数据！");
    return;
  }
  // if (rowDatas[0].status == 1) {
  //     Message.warning("不能删除已审核的入库记录！");
  //     return;
  // }
  post({
    url: '/dwWms/ProductStockOut/delete',
    data: rowIds
  }).then(({code, data}) => {
    if (code === 200) {
      Message.success({
        content: "删除成功",
        duration: 5000,
      });
      loadInStocks();
    }
  })
}


// 仓库名称下拉框下拉数据
const focusSel = () => {
  selCxAll({"firmId": "", warehouseTypeName: "成品仓"});
}
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
  if (value) {
    const ob = {firmId: value, deleteState: 0, warehouseTypeName: "成品仓"}
    loading.value = true;
    selCxAll(ob);
    options.value = pageData.nameList;
    loading.value = false;
  } else {
    options.value = []
  }
};

function selCxAll(val: any) {
  // let ob = ''
  // if (pageData.sideTitle == '新增织厂送货入库单') {
  //     ob = gridOption.value.getSelectedRows().map((item: any) => {
  //         return item.companyId
  //     })
  //     inStockData.companyId = ob[0]
  //     // console.log(ob, '多年以后我看着泪流不止');
  // } else {
  //     ob = gridOption1.value.getSelectedRows().map((item: any) => {
  //         return item.companyId
  //     })
  //     inStockData.companyId = ob[0]
  //     // console.log(ob, '我的父亲已经老得像一张旧报纸');
  // }


  post({
    url: "/dwWms/warehouse/getWarehouseByPara",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      pageData.nameList = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

const chanON = (res: any) => {
  pageData.nameList.forEach((o: any) => {
    if (inStockData.warehouseName == o.warehouseName) {
      inStockData.warehouseId = o.value
      inStockData.companyId = o.firmId
    }
  })
}
// 流转卡回车事件
const huiche = (item: any) => {
  // // loadInStocks();
  // console.log(item, 'look look ');
  // console.log(inStockData.circulatCard, 'look look222 ');
  post({
    url: "/dwWms/ProductStockOut/getProductStockOutDetail",
    // data: CCobject
    data: {rawCirculatCard: inStockData.circulatCard}

  }).then((res: any) => {
    if (res.code === 200) {
      // inStockData.stockInCode = res.data
      // summaryList.value =
      summaryList.value = res.data.productStockOutDetail,
          detailList.value = res.data.productStockBarcode
    }
  })
}
// 新增入库事件
const addHandler = (ress: any) => {
  for (var key in inStockData) {
    if (key == "id") {
      inStockData[key] = null;

    } else {
      inStockData[key] = '';
    }
  }
  summaryList.value = []
  detailList.value = []
  inStockData.stockOutDate = dayjs().format('YYYY-MM-DD')
  // 单号自动生成事件
  post({
    url: "/dwWms/ProductStockOut/getCodeGenerate",
    // data: CCobject
    data: {}

  }).then((res: any) => {
    if (res.code === 200) {
      inStockData.stockOutCode = res.data
    }
  })
  pageData.sideTitle = "新增成品出库";
  pageData.showAdd = true;
}
const pagination = usePagination(loadInStocks);
const changeLX = () => {
  if (inStockData.stockOutTypeId == 101) {
    inStockData.stockOutTypeName = "成品入库"
  } else if (inStockData.stockOutTypeId == 102) {
    inStockData.stockOutTypeName = "生产退库"
  } else if (inStockData.stockOutTypeId == 103) {
    inStockData.stockOutTypeName = "客户退库"
  }
}
const changeLZ = (res: any) => {
  // console.log(res, '哈哈哈哈');
  post({
    url: "/aps/circulatCard/getList",
    data: {flowCardCode: res}

  }).then((res: any) => {
    if (res.code === 200) {
      inStockData.planOrderCode = res.data[0].orderCode
      inStockData.customName = res.data[0].customName
      inStockData.rawCirculatCard = res.data[0].flowCardCode
    }
  })
}
</script>
<script lang="ts">
export default {
  name: "ProductInStock",
}
</script>

<style scoped>
.arco-select-dropdown {
  width: 150px;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.chinaNO1) {
  background-color: #f9a633;
  color: #fff;
  margin-left: 30px;
  text-align: center;
  font: 600 18px/18px "";
}

:deep(#onlyNO11) {
  width: 700px !important
}

:deep(.onlyNo1) {
  width: 50% !important
}

:deep(.arco-row-nowrap) {
  margin-top: 10px;
}
</style>